<div class="animated fadeIn">
    <div class="row">
        <div class="col-lg-12">
            <div class="card">
                <div class="card-header">
                    <i class="fas fa-align-justify"></i>空间管理
                </div>
                <div class="card-body">

                    <div class="layui-row">
                        <div class="layui-col-md6">

                            <div class="container">
                                <div class="layui-btn-group" th:if="${session.ActiveUser.isAdmin()}">
                                    <button type="button" class="layui-btn layui-btn-sm uploadDialog" data-toggle="modal"
                                            data-target="#addDisk">
                                        <i class="fas fa-plus-square"></i> 新建磁盘
                                    </button>
                                </div>

                                <table class="layui-disk" id="LAY_table_disks" lay-filter="disk">
                                </table>

                                <script type="text/html" id="diskOpsBar">
                                    <div class="layui-btn-group">
                                        <button class="layui-btn layui-btn-normal layui-btn-sm" lay-event="edit-disk">
                                            <i class="fas fa-edit" title="编辑"></i>
                                        </button>
                                        <button class="layui-btn layui-btn-warm layui-btn-sm" lay-event="auth-disk">
                                            <i class="fas fa-user-secret" title="授权"></i>
                                        </button>
                                        <button class="layui-btn layui-btn-danger layui-btn-sm" lay-event="delete">
                                            <i class="fas fa-trash-alt" title="删除"></i>
                                        </button>
                                    </div>
                                </script>
                            </div>
                        </div>
                        <div class="layui-col-md6" style="float: right">

                            <div class="container">
                                <div class="layui-btn-group">
                                    <a class="layui-btn layui-btn-sm" lay-filter="add"><i class="fas fa-plus-square"></i> 新建目录</a>
                                    <a id="addSubBtn" class="layui-btn-disabled layui-btn layui-btn-sm" lay-filter="addChild"><i
                                            class="far fa-plus-square"></i> 新建子目录</a>
                                    <a id="renameFolderBtn" class="layui-btn-disabled layui-btn layui-btn-sm layui-btn-normal"
                                       lay-filter="update"><i class="fas fa-edit"></i> 修改</a>
                                    <a id="authFolderBtn" class="layui-btn-disabled layui-btn layui-btn-sm layui-btn-warm"
                                       lay-filter="auth-folder"><i class="fas fa-user-secret"></i> 授权</a>
                                    <a id="deleteFolderBtn" class="layui-btn-disabled layui-btn layui-btn-sm layui-btn-danger"
                                       lay-filter="delete"><i class="fas fa-trash-alt"></i> 删除</a>
                                </div>
                                <table class="layui-table" id="LAY_table_folders" lay-filter="folder">
                                </table>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <!--/.row-->
        </div>
    </div>
</div>

<!-- 模态框 -->
<div class="modal fade" id="addDisk">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">

            <!-- 模态框头部 -->
            <div class="modal-header">
                <h4 class="modal-title">磁盘空间</h4>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>

            <!-- 模态框主体 -->
            <div class="modal-body">
                <div class="table-responsive" style="text-align: center">
                    <form method="POST" th:action="@{'./disk/save'}">
                        <table class="table table-hover">
                            <tr>
                                <td align="right">磁盘空间名:</td>
                                <td>
                                    <div class="template-input-icon-container">
                                        <i class="fas fa-hdd"></i>
                                        <input type="text" class="form-control"
                                               placeholder="磁盘空间名"
                                               required="required"
                                               id="diskName" name="diskName"/>
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td align="right">所有者名称:</td>
                                <td>
                                    <div class="template-input-icon-container">
                                        <i class="fas fa-user-secret"></i>
                                        <input type="text" class="form-control"
                                               placeholder="所有者名称"
                                               required="required"
                                               id="owner" name="owner"/>
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td align="right">所有者类别:</td>
                                <td>
                                    <select id="authType" name="authType"
                                            class="select custom-select">
                                        <option th:each="entry : ${authTypeMap}"
                                                th:value="${entry.key}"
                                                th:text="${entry.value}">所有者类别
                                        </option>
                                    </select>
                                </td>
                            </tr>
                        </table>
                        <input type="submit" value="保存" class="btn btn-success"/>
                    </form>
                </div>
            </div>
            <!-- 模态框底部 -->
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭
                </button>
            </div>

        </div>
    </div>
</div>

<script th:inline="javascript">
    /*<![CDATA[*/

    layui.config({
        base: '../lib/layui/treegrid/'
    }).use(['laytpl', 'treegrid', "table"], function () {
        var laytpl = layui.laytpl,
            table = layui.table,
            treegrid = layui.treegrid;
        treegrid.config.render = function (viewid, data) {
            var view = document.getElementById(viewid).innerHTML;
            return laytpl(view).render(data) || '';
        };

        var diskId = null;

        var optDisk = {
            elem: '#LAY_table_disks',
            id: 'disk-data',
            url: '/api/disk/list',
            height: '520',
            page: true,
            limit: 10,
            limits: [10, 50, 100, 200],
            cols: [
                [
                    {field: 'id', title: 'ID'},
                    {field: 'name', title: '磁盘名称', event: 'diskName'},
                    {field:'authorizations',title:'授权信息'},
                    {
                        title: '操作',
                        align: 'center',
                        toolbar: '#diskOpsBar'
                    }
                ]
            ],
            done: function (res, curr, count) {
                $("[data-field='id']").css('display', 'none');
            }
        };

        //方法级渲染
        table.render(optDisk);

        var folderTreeGrid = null;

        table.on('tool(disk)', function (obj) {
            var data = obj.data;
            if (obj.event === 'diskName') {
                diskId = data.id;
                loadDiskFolders(diskId);
            } else if (obj.event === 'edit-disk') {
                layer.prompt(
                    {
                        title: '请输入新的磁盘名称',
                        success: function (layerInput) {
                            layerInput.find('input').on('keydown', function () {
                                if (event.keyCode === 13) {
                                    prompt_service(event.target.value);
                                }
                            })
                        }
                    },
                    function (value) {
                        prompt_service(value);
                    }
                );

                function prompt_service(inputParam) {
                    var codeParam = encodeURI(inputParam);
                    $.ajax({
                        type: "POST",
                        url: "/api/disk/rename?diskId=" + data.id + "&newName=" + codeParam,
                        contentType: 'application/json; charset=utf-8',
                        dataType: "json",
                        success: function (value) {
                            var tableDisk = table.render(optDisk);
                            tableDisk.reload();
                        }
                    });
                    layer.closeAll();
                }
            } else if (obj.event === 'auth-disk') {
                layer.open({
                    type: 2,
                    title: '磁盘授权',
                    area: ['560px', '420px'],
                    resize: false,
                    content: 'disk/auth?id=' + data.id + '&target=DISK',
                    zIndex: layer.zIndex,
                    success: function (layero) {
                        layer.setTop(layero);
                    }
                });
            } else if (obj.event === 'delete') {
                layer.confirm('真的删除磁盘: ' + data.name + ' 吗？', {title: "删除确认"}, function (index) {
                    $.ajax({
                        type: "POST",
                        url: "/api/disk/delete",
                        contentType: 'application/json; charset=utf-8',
                        data: data.id, //可选参数
                        dataType: "json",
                        success: function (value) {
                            var result = JSON.parse(value);
                            if (result == true) {
                                layer.alert('磁盘【' + data.name + '】删除成功!', {
                                    icon: 6, btn: ['确认'], yes: function (index) {
                                        obj.del();
                                        layer.close(index);
                                        var tableDisk = table.render(optDisk);
                                        tableDisk.reload();
                                    }
                                });
                            } else {
                                layer.alert("磁盘删除失败!", {icon: 2});
                            }
                            layer.close(index);
                        }
                    });
                });
            }
        });

        $('.layui-btn').on('click', function () {
            switch ($(this).attr('lay-filter')) {
                case 'add': {
                    if (folderTreeGrid === null) {
                        promptAddFolder(null, 'sibling');
                    } else {
                        var row = folderTreeGrid.getRow();
                        if (row === null) {
                            layer.msg('请选择一个目录！');
                        } else {
                            promptAddFolder(row, 'sibling');
                        }
                    }
                }
                    break;
                case 'addChild': {
                    var row = folderTreeGrid.getRow();
                    if (row === null) {
                        layer.msg('请选择一个目录！');
                    } else {
                        promptAddFolder(row, 'child');
                    }

                }
                    break;
                case 'update': {
                    var row = folderTreeGrid.getRow();
                    layer.prompt(
                        {
                            title: '请输入新的目录名称',
                            success: function (layerInput) {
                                layerInput.find('input').on('keydown', function () {
                                    if (event.keyCode === 13) {
                                        prompt_service(event.target.value, row);
                                    }
                                })
                            }
                        },
                        function (value) {
                            prompt_service(value, row);
                        }
                    );

                    function prompt_service(_newName, _row) {
                        $.ajax({
                            type: "POST",
                            url: "/api/folder/rename?id=" + _row.id + "&newName=" + _newName,
                            contentType: 'application/json; charset=utf-8',
                            dataType: "json",
                            success: function (value) {
                                folderTreeGrid.updateNode(value, _row.id);
                            }
                        });
                        layer.closeAll();
                    }
                }
                    break;
                case 'auth-folder': {
                    var row = folderTreeGrid.getRow();
                    layer.open({
                        type: 2,
                        title: '目录授权',
                        area: ['560px', '420px'],
                        resize: false,
                        content: 'disk/auth?id=' + row.id + '&target=FOLDER',
                        zIndex: layer.zIndex,
                        success: function (layero) {
                            layer.setTop(layero);
                        }
                    });
                    //row.text += 'auth-folder';
                    //folderTreeGrid.updateNode(row, row.id);
                }
                    break;
                case 'delete': {
                    var row = folderTreeGrid.getRow();
                    folderTreeGrid.deleteNode(row.id);
                }
                    break;
            }
        });

        function promptAddFolder(selectedRow, addType) {
            layer.prompt(
                {
                    title: '请输入目录名',
                    success: function (layerInput) {
                        layerInput.find('input').on('keydown', function () {
                            if (event.keyCode === 13) {
                                saveFolderService(event.target.value, selectedRow, addType);
                            }
                        })
                    }
                },
                function (value) {
                    saveFolderService(value, selectedRow, addType);
                }
            );
        }

        function saveFolderService(folderName, selectedRow, addType) {
            var parentId = null;
            var parentType = null;
            switch (addType) {
                case 'sibling': {
                    if (selectedRow === null) {
                        parentId = diskId;
                    } else {
                        parentId = selectedRow.parentId;
                    }
                    if (parentId === diskId) {
                        parentType = 'DISK';
                    } else {
                        parentType = 'FOLDER';
                    }
                }
                    break;
                case 'child': {
                    parentId = selectedRow.id;
                    parentType = 'FOLDER';
                }
                    break;
            }
            $.ajax({
                type: "POST",
                url: "/api/folder/save?name=" + folderName + "&parentId=" + parentId + "&parentType=" + parentType + "&diskId=" + diskId,
                contentType: 'application/json; charset=utf-8',
                //data: JSON.stringify(postData), //可选参数
                dataType: "json",
                success: function (value) {
                    if (folderTreeGrid === null) {
                        loadDiskFolders(diskId);
                    } else {
                        switch (addType) {
                            case 'sibling': {
                                folderTreeGrid.insertNode(value, parentId);
                            }
                                break;
                            case 'child': {
                                folderTreeGrid.insertChild(value, parentId);
                            }
                                break;
                        }
                    }
                }
            });
            layer.closeAll();
        }

        function loadDiskFolders(_diskId) {
            $.ajax({
                type: "GET",
                url: "/api/folder/list?diskId=" + _diskId,
                contentType: 'application/json; charset=utf-8',
                //data: data.id, //可选参数
                dataType: "json",
                success: function (value) {
                    if (value.length > 0) {
                        folderTreeGrid = treegrid.createNew({
                            elem: 'LAY_table_folders',
                            view: 'folderView',
                            data: {rows: value},
                            id: 'id',
                            root: _diskId,
                            parentid: 'parentId',
                            singleSelect: true
                        });
                        folderTreeGrid.build();
                        $('#addSubBtn').removeClass('layui-btn-disabled');
                        $('#renameFolderBtn').removeClass('layui-btn-disabled');
                        $('#authFolderBtn').removeClass('layui-btn-disabled');
                        $('#deleteFolderBtn').removeClass('layui-btn-disabled');
                    } else {
                        layer.msg('该磁盘内无子目录！');
                        folderTreeGrid = null;
                        $('#addSubBtn').addClass('layui-btn-disabled');
                        $('#renameFolderBtn').addClass('layui-btn-disabled');
                        $('#authFolderBtn').addClass('layui-btn-disabled');
                        $('#deleteFolderBtn').addClass('layui-btn-disabled');
                    }
                }
            });
        }

        /*]]>*/
    });
</script>
<!--模板 js start-->
<script id="folderView" type="text/html">
    <table class="layui-table">
        <thead>
        <tr>
            <th>目录名称</th>
        </tr>
        </thead>
        <tbody>
        {{# layui.each(d.rows,function(index,r){ }}
        <tr>
            <td><input type="checkbox"/>{{r.name}}</td>
        </tr>
        {{# }); }}
        </tbody>
    </table>
</script>
<!--模板 end-->